package com.je.meta.service.upgrade.impl;

import com.je.common.base.DynaBean;
import com.je.common.base.upgrade.PackageResult;
import com.je.common.base.upgrade.UpgradeResourcesEnum;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.service.upgrade.InstallResourceDTO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 打包文档数据
 */
@Service("upgradeOfficeDataDate")
public class UpgradeOfficeDataDate extends AbstractUpgradeMetaDate<PackageResult> {

    public UpgradeOfficeDataDate() {
        super(UpgradeResourcesEnum.OFFICE_DATA);
    }

    //子数据
    private static final String FIELD_CHILD_CODE = "fieldChild";

    @Override
    public void packUpgradeMetaDate(PackageResult packageResult, DynaBean upgradeBean) {
        List<String> list = getSourceIds(upgradeBean);
        if (list == null || list.size() == 0) {
            return;
        }
        packageResult.setProductOfficeData(packageResources(packageResult, list));
    }

    @Override
    public void installUpgradeMetaDate(String upgradeInstallId, List<DynaBean> list, String productCode, Map<String, Object> customerParameter) {
        //主数据
        installResources(buildAbstractDto(upgradeInstallId, list, productCode));
        //子数据 导入SHEET明细
        List<DynaBean> allFieldList = getChildList(list, FIELD_CHILD_CODE);
        installResources(new InstallResourceDTO.Builder()
                .upgradeInstallId(upgradeInstallId)
                .list(allFieldList)
                .productCode(productCode)
                .identifier("JE_OFFICE_FIELD_ID")
                .tableCode("JE_OFFICE_FIELD")
                .logAdd(false)
                .build());
    }

    @Override
    public List<DynaBean> packageResources(PackageResult packageResult, List<String> resourceIds) {
        List<DynaBean> beanList = metaService.select(upgradeResourcesEnum.getTableCode(), ConditionsWrapper.builder()
                .in(upgradeResourcesEnum.getContentCode(), resourceIds));

        List<DynaBean> childList = metaService.select("JE_OFFICE_FIELD",
                ConditionsWrapper.builder().in("JE_OFFICE_DATA_ID", resourceIds));
        Map<String, List<DynaBean>> map = new HashMap<>();
        for (DynaBean dynaBean : childList) {
            String dataId = dynaBean.getStr("JE_OFFICE_DATA_ID");
            if (map.get(dataId) == null) {
                map.put(dataId, new ArrayList<>());
            }
            map.get(dataId).add(dynaBean);
        }

        for (DynaBean dynaBean : beanList) {
            dynaBean.set(FIELD_CHILD_CODE, map.get(dynaBean.getPkValue()));
        }
        return beanList;
    }

    @Override
    public List<DynaBean> extractNecessaryData(PackageResult packageResult) {
        return packageResult.getProductOfficeData();
    }


}
